<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j list page-list flash-sale">
    <div class="content">
      <div class="list-banner">
        <img
          src="@/assets/images/flash-banner.jpg"
          alt
        >
      </div>
      <div class="goods-list">
        <div class="list-con">
          <div
            v-for="(item, index) in dataList"
            :key="index"
            class="item sell-out"
            @click="toSeckillDet(item.prodId)"
          >
            <div
              v-if="!item.seckillSearchVO.seckillTotalStocks"
              class="sellout-text"
            >
              {{ $t('spike.alreadyFinished') }}
            </div>
            <div class="goods-img">
              <img
                v-if="item.pic"
                :src="checkFileUrl(item.pic)"
                alt
                @error="handlePicError"
              >
              <img
                v-else
                src="@/assets/img/def.png"
                alt
              >
            </div>
            <div
              v-if="countdownList.length"
              class="time-box"
            >
              <div
                class="text"
                style="text-align:center"
              >
                {{
                  countdownList[index].obj.signs !== 0 ? $t('spike.stillToGoBeforeTheEnd') : $t('spike.stillToGoBeforeTheStart')
                }}
              </div>
              <div class="time">
                <template v-if="countdownList[index].obj.day">
                  <span class="time-item">{{
                    countdownList[index].obj.day
                  }}</span>
                  <span class="time-text">{{ $t('day') }}</span>
                </template>
                <span class="time-item">{{
                  countdownList[index].obj.hou
                }}</span>
                <span class="time-text">:</span>
                <span class="time-item">{{
                  countdownList[index].obj.min
                }}</span>
                <span class="time-text">:</span>
                <span class="time-item">{{
                  countdownList[index].obj.sec
                }}</span>
              </div>
            </div>
            <div class="goods-name">
              {{ item.prodName }}
            </div>
            <div class="rest-number">
              <div class="number-box">
                <div
                  class="percent"
                  :style="'width:' + item.salesRatio + '%'"
                />
              </div>
              <div class="number-text">
                {{ $t('spike.sold') }}
                <span class="number">{{ item.salesRatio }}%</span>
              </div>
            </div>
            <div class="goods-price">
              <div class="price">
                ￥
                <span class="big">{{ parsePrice(item.activityPrice)[0] }}</span>
                .{{ parsePrice(item.activityPrice)[1] }}
              </div>
              <div
                v-if="item.activityOriginalPrice > item.activityPrice"
                class="old-price"
              >
                ￥{{ toPrice(item.activityOriginalPrice) }}
              </div>
            </div>
          </div>
        </div>
        <!-- 页码 -->
        <pagination
          v-model="current"
          :pages="pages"
          @change-page="getSearchProdPage"
        />
        <!-- /页码 -->

        <!-- 商品列表为空 -->
        <empty-all-tips
          v-if="isEmpty"
          :text="$t('sorryNoRelatedProducts')"
          :back="$t('lookAtOther')"
          :back-path="'/list'"
        />
        <!-- 商品列表为空 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import * as util from '@/utils/index.js'
import defPng from '@/assets/img/def.png'

// 过渡效果设置
const style = document.createElement('style')
const cssText = 'a{-webkit-transition: all .2s ease;-moz-transition: all .2s ease;-ms-transition: all .2s ease;-o-transition: all .2s ease;transition: all .2s ease;}'
style.innerHTML = cssText
const head = document.getElementsByTagName('head')[0]
head.appendChild(style)

const route = useRoute()
const router = useRouter()

const current = ref(route.query.current || 1) // 当前页数
onMounted(() => {
  // 设置网页标题
  document.title = $t('commonHead.spikeSpecial')
  current.value = parseInt(route.query.c) || 1
  getSearchProdPage(current.value)
})

/**
 * 加载默认图片
 */
const handlePicError = (e) => {
  e.target.src = defPng
}

const isEmpty = ref(false)
const pages = ref(1) // 总页数
const dataList = ref([]) // 秒杀列表
const countdownList = ref([]) // 秒杀倒计时列表
/**
 * 请求商品列表
 */
const getSearchProdPage = (current) => {
  isEmpty.value = false
  const param = {
    current,
    size: 20, // 每页显示多少条
    prodType: 2,
    isActive: 1 // 过滤掉活动商品
  }
  http.get('/search/page', {
    params: param
  }).then(({ data }) => {
    pages.value = data.pages
    const countdownListPar = []
    const startTimee = []
    data.records[0].products = data.records[0].products.filter(el => el.seckillSearchVO)
    dataList.value = data.records[0].products
    isEmpty.value = !dataList.value.length
    // 计算秒杀时间
    data.records[0].products.forEach((el) => {
      // 已售百分比
      el.salesRatio = el.seckillSearchVO.seckillOriginStocks <= 0 ? 100 : parseInt(((el.seckillSearchVO.seckillOriginStocks - el.seckillSearchVO.seckillTotalStocks) / el.seckillSearchVO.seckillOriginStocks) * 100)

      if (el.salesRatio === 0 && el.seckillSearchVO.seckillOriginStocks - el.seckillSearchVO.seckillTotalStocks) { // 秒杀进度不足1%，但也要显示1%
        el.salesRatio = Math.ceil(((el.seckillSearchVO.seckillOriginStocks - el.seckillSearchVO.seckillTotalStocks) / el.seckillSearchVO.seckillOriginStocks) * 100)
      }

      const betweenTimestamp = util.betweenTimestamp(util.dateToTimestamp(el.seckillSearchVO.startTime), util.dateToTimestamp(el.seckillSearchVO.endTime))

      // 开始时间存入数组
      startTimee.push({
        startTime: util.dateToTimestamp(el.seckillSearchVO.startTime)
      })

      countdownListPar.push({
        obj: util.betweenTime(betweenTimestamp),
        stamp: betweenTimestamp
      })
    })

    countdownList.value = countdownListPar
    countdown(startTimee)
  })
}

let timer = null
// 倒计时
const countdown = (startTimee) => {
  // signs = 0 是距离开始  signs = 1 是距离结束
  const newTime = new Date().getTime()
  countdownList.value.forEach((countdown, index) => {
    countdown.stamp = countdown.stamp > 0 ? countdown.stamp - 1000 : countdown.stamp + 1000
    countdown.obj = util.betweenTime(countdown.stamp)
    // 现在距离秒杀开始的时间判断
    if (newTime < startTimee[index].startTime) {
      countdown.obj.signs = 0
    }

    if (countdown.stamp < 1000) {
      countdown.obj.signs = 0
    }
  })

  const countdownFlag = countdownList.value.some((item) => {
    if (item.obj.day === '00' && item.obj.hou === '00' && item.obj.min === '00' && item.obj.sec === '00') {
      clearTimeout(timer)
      getSearchProdPage(current)
      return true
    }
    return false
  })

  if (!countdownFlag) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      countdown(startTimee)
    }, 1000)
  }
}

/**
 * 跳转秒杀详情
 */
const toSeckillDet = (prodId) => {
  const newPage = router.resolve({ path: '/detail', query: { prodId } })
  window.open(newPage.href, '_blank', 'noopener,noreferrer')
}

/**
 * 处理价格样式
 */
const toPrice = (val) => {
  val = Number(val)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，没有则自动补0
  return (val.toFixed(2))
}

const parsePrice = (val) => {
  val = Number(val)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

onBeforeUnmount(() => {
  clearTimeout(timer)
})

</script>

<style lang="scss" scoped>
@use "../list/index";
</style>
